<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>


    <!--卡片视图区域-->
    <el-card>
      <!--提示文本-->
      <el-alert
          title="注意，只允许为第三级分类设置相关参数！"
          type="warning"
          show-icon
          :closable="false">
      </el-alert>

      <!--选择商品分类区域-->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!--选择商品分类的级联选择框-->
          <el-cascader ref="cascader"
                       v-model="selectCateKeys"
                       :options="cateList"
                       :props="{
                  expandTrigger: 'hover',
                  value: 'cat_id',
                  label: 'cat_name'}"
                       @change="handleChange"
                       clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!--tab 标签页区域-->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick" class="cat_opt">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" @click="addParamDialogVisible = true" size="mini" :disabled="isSelected">添加参数
          </el-button>
          <!--动态参数渲染区域-->
          <el-table :data="manyTableData" border stripe>
            <!--展开列-->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                    :key="i"
                    v-for="(tag, i) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="TagClose(i, scope.row)">
                  {{ tag }}
                </el-tag>
                <el-input
                    class="input-new-tag"
                    v-if="scope.row.tagInputVisible"
                    v-model="scope.row.tagInput"
                    ref="tagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showTagInput(scope.row)">+ 添加新参数
                </el-button>
              </template>
            </el-table-column>
            <!--索引列-->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="mini" @click="showEditDialog(scope.row.attr_id)" type="primary" icon="el-icon-edit">
                  编辑
                </el-button>
                <el-button size="mini" @click="removeCat(scope.row.attr_id)" type="danger" icon="el-icon-delete">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" @click="addParamDialogVisible = true" size="mini" :disabled="isSelected">添加属性
          </el-button>
          <!--静态属性渲染区域-->
          <el-table :data="onlyTableData" border stripe>
            <!--展开列-->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                    :key="i"
                    v-for="(tag, i) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="TagClose(i, scope.row)">
                  {{ tag }}
                </el-tag>
                <el-input
                    class="input-new-tag"
                    v-if="scope.row.tagInputVisible"
                    v-model="scope.row.tagInput"
                    ref="tagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showTagInput(scope.row)">+ 添加新参数
                </el-button>
              </template>
            </el-table-column>
            <!--索引列-->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="mini" @click="showEditDialog(scope.row.attr_id)" type="primary" icon="el-icon-edit">
                  编辑
                </el-button>
                <el-button size="mini" @click="removeCat(scope.row.attr_id)" type="danger" icon="el-icon-delete">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>


    <!--添加参数的对话框-->
    <el-dialog :title="'添加' + titleText"
               :visible.sync="addParamDialogVisible" width="30%"
               @close="addParamDialogClosed">
      <el-form :model="addParamForm"
               ref="addParamForm"
               :rules="addParamFormRules"
               label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">添加</el-button>
      </div>
    </el-dialog>

    <!--修改参数对话框-->
    <el-dialog :title="'修改' + titleText"
               :visible.sync="editParamDialogVisible" width="30%"
               @close="editParamDialogClosed">
      <el-form :model="editParamForm"
               ref="editParamForm"
               :rules="editParamFormRules"
               label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Params",
  data() {
    return {
      cateList: [],
      // 选择的key
      selectCateKeys: [],
      // 标签页绑定值
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 属性参数数据
      onlyTableData: [],
      // 控制添加参数的对话框是否显示
      addParamDialogVisible: false,
      // 添加参数的表单
      addParamForm: {},
      // 添加表单的验证规则对象
      addParamFormRules: {
        attr_name:
            {required: true, message: '请输入名称', trigger: 'blur'}
      },
      editParamDialogVisible: false,
      editParamForm: {},
      editParamFormRules: {
        attr_name:
            {required: true, message: '请输入名称', trigger: 'blur'}
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有的商品分类
    async getCateList() {
      const {data: res} = await this.$http.get('categories')

      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }

      this.cateList = res.data
      // console.log(res.data)
      // console.log(this.cateList)
    },
    // 获取参数的详细列表
    async getParamsData() {
      const {data: res} =
          await this.$http.get(
              `categories/${this.cateId}/attributes`,
              {params: {sel: this.activeName}})

      if (res.meta.status !== 200) {
        return this.$message.error("获取分类参数失败")
      }


      // 在赋值之前，将 attr_vals 以 ',' 为分隔符，将字符串转成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 为每一个 item 添加
        // 添加参数标签字符的显示
        item.tagInputVisible = false
        // 添加参数标签的字符
        item.tagInput = ''
      })

      console.log(res.data)

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }

    },
    // 级联选中框的选中项变化
    handleChange() {
      if (this.selectCateKeys.length === 0) {
        return this.clearHandle()
      }
      if(this.selectCateKeys.length !== 3) {
        return this.selectCateKeys = []
      }

      // 级联选中框发生变化请求
      this.getParamsData()
    },
    // 级联选中框清除值
    clearHandle() {
      // console.log("清除了")
      this.manyTableData = []
      this.onlyTableData = []
    },
    // 切换标签页触发
    handleClick(tab, event) {
      // console.log(tab, event)

      // 切换标签页发起请求参数
      if (!this.isSelected) {
        this.getParamsData()
      }
    },
    // 监听添加参数对话框的关闭
    addParamDialogClosed() {
      this.$refs.addParamForm.resetFields()
    },
    // 点击按钮，添加参数
    addParams() {
      this.$refs.addParamForm.validate(async valid => {
        if (!valid) return

        const {data: res} = await this.$http.post(
            `categories/${this.cateId}/attributes`,
            {
              attr_name: this.addParamForm.attr_name,
              attr_sel: this.activeName
            })

        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }

        this.$message.success('添加参数成功')
        this.addParamDialogVisible = false
        this.getParamsData()
      })
    },
    // 点击按钮，显示修改参数对话框
    async showEditDialog(attr_id) {

      // 查询当前参数的信息
      const {data: res} = await this.$http.get(
          `categories/${this.cateId}/attributes/${attr_id}`,
          {params: {attr_sel: this.activeName}})
      if (res.meta.status !== 200) {
        return this.$message.error('查询参数失败')
      }

      this.editParamForm = res.data

      this.editParamDialogVisible = true;


    },
    // 关闭修改分类参数对话框
    editParamDialogClosed() {
      this.$refs.editParamForm.resetFields()
      this.editParamForm = {}
    },
    // 点击按钮修改分类参数
    editParams() {
      this.$refs.editParamForm.validate(async valid => {
        if (!valid) return

        const {data: res} = await this.$http.put(
            `categories/${this.cateId}/attributes/${this.editParamForm.attr_id}`,
            this.editParamForm)

        if (res.meta.status !== 200) {
          return this.$message.error('编辑失败')
        }

        this.$message.success('编辑成功')

        this.editParamDialogVisible = false
        this.getParamsData()
      })
    },
    // 按下按钮删除参数
    async removeCat(attr_id) {

      const confirmRes = await this.$confirm('此操作将永久删除参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmRes)

      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }

      this.$message.success('删除成功')

      this.getParamsData()
    },
    // 删除动态参数下的标签
    TagClose(i, tag) {

      tag.attr_vals.splice(i, 1)

      // 发起更新请求
      this.updateManyParamTags(tag)
    },
    // 添加参数标签显示
    showTagInput(item) {
      item.tagInputVisible = true
      // 让 input 自动获得焦点
      // $nextTick 方法的作用，就时当前页面上的元素被重新渲染之后，才会指定回调函数的代码
      this.$nextTick(_ => {
        this.$refs.tagInput.$refs.input.focus()
      })
    },
    // 添加动态参数下的标签
    handleInputConfirm(tag) {
      // console.log(tags)
      let tagInput = tag.tagInput
      if (tagInput.trim().length !== 0) {
        tag.attr_vals.push(tagInput)
      }

      tag.tagInputVisible = false
      tag.tagInput = ''

      // 发起更新请求
      this.updateManyParamTags(tag)
    },
    // 对动态参数下的标签进行更新
    async updateManyParamTags(tag) {
      console.log(tag)
      const {data: res} = await this.$http.put(
          `categories/${this.cateId}/attributes/${tag.attr_id}`,
          {
            attr_name: tag.attr_name,
            attr_sel: tag.attr_sel,
            attr_vals: tag.attr_vals.join(',')
          })

      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
    }
  },
  computed: {
    // 如果按钮需要被禁用返回 true ,否则返回 false
    isSelected() {
      // console.log(this.selectCateKeys)
      return this.selectCateKeys.length < 2
    },
    // 当前选中的三级分类 id
    cateId() {
      if (this.selectCateKeys.length > 0) {
        // console.log(this.selectCateKeys[this.selectCateKeys.length - 1])
        return this.selectCateKeys[this.selectCateKeys.length - 1]
      }
      return null
    },
    // 动态计算标题文字
    titleText() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }

  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
  margin-bottom: 15px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>